# -*- coding: utf-8 -*-
from datetime import datetime

from flask import Blueprint, request, url_for, redirect, jsonify

from application import db
from common.libs.render_helper import ops_render
from web.models.member.Member import Member

route_member = Blueprint('member_page', __name__)


@route_member.route("/index")
def index():
    # return ops_render("member/index.html")
    member_list = Member.query.all()
    context = {'member_list': member_list}
    return ops_render("member/index.html", context)


@route_member.route("/info")
def info():
    # return ops_render("member/info.html")
    context = {}
    req = request.args
    # 获取查询账号请求的id，如果没输入返回0
    id = int(req.get("id", 0))
    # 定义一个跳转对象
    reback_url = url_for('member_page.index')
    if id < 1:
        return redirect(reback_url)  # 如果没输入则重定向至首页
    info = Member.query.filter_by(id=id).first()  # 查询账号列表uid符合的
    if not info:  # 如果搜索结果为空
        return redirect(reback_url)
    context["info"] = info  # 当前要操作的会员对象
    return ops_render("member/info.html", context)


@route_member.route("/set", methods=['GET', 'POST'])
def set():
    # return ops_render("member/set.html")
    if request.method == "GET":
        context = {}
        # args返回请求的参数，values返回请求中的参数和form
        req = request.args
        id = int(req.get("id", 0))
        reback_url = url_for('member_page.index')
        if id < 1:
            return redirect(reback_url)
        info = None
        if id:  # 所以如果获取到请求的id参数，则是通过点击修改进来的页面
            info = Member.query.filter_by(id=id).first()
        context["info"] = info
        return ops_render("member/set.html", context)

    if request.method == 'POST':
        resp = {"code": 200, "msg": "操作成功~", "data": {}}
        req = request.values
        id = req["id"] if "id" in req else 0
        nickname = req["nickname"] if "nickname" in req else ""
        if nickname is None or len(nickname) < 1:
            resp['code'] = -1
            resp['msg'] = '请输入符合规范的名称'
            return jsonify(resp)
        member_info = Member.query.filter_by(id=id).first()
        if not member_info:
            resp['code'] = -1
            resp['msg'] = '需要修改的会员不存在'
            return jsonify(resp)

        # 持久化修改的数据
        member_info.nickname = nickname
        member_info.updated_time = datetime.now()
        db.session.add(member_info)
        db.session.commit()
        return jsonify(resp)


@route_member.route("/comment")
def comment():
    return ops_render("member/comment.html")

# 删除操作
@route_member.route('/ops', methods=['POST'])
def ops():
    resp = {"code": 200, "msg": "操作成功", "data": {}}
    req = request.values
    act = req["act"] if "act" in req else ""
    id = req["id"] if "id" in req else 0
    print('获取到的数据:', act, id)

    # 非法操作判断逻辑
    if act not in ["remove", "recover"]:
        resp["code"] = -1
        resp["msg"] = "操作有误"
        return jsonify(resp)
    if not id:
        resp["code"] = -1
        resp["msg"] = "请选择要操作的会员账号"
        return jsonify(resp)

    # 查询数据库id符合的数据
    member_info = Member.query.filter_by(id=id).first()
    if not member_info:
        resp["code"] = -1
        resp["msg"] = "指定会员不存在"
        return jsonify(resp)

    # 在js里依据状态0和1来决定显示的内容
    if act == "remove":  # 变成删除状态
        member_info.status = 0
    elif act == "recover":  # 变成不删除状态
        member_info.status = 1  # 回复状态
    member_info.updated_time = datetime.now()
    # 提交数据库
    db.session.add(member_info)
    db.session.commit()
    return jsonify(resp)